package org.pupil.register.zookeeper;

import org.pupil.common.Cache;
import org.pupil.common.Service;
import org.pupil.common.URL;
import org.pupil.register.RegistryService;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: Zookeeper注册中心的抽象层，封装更新本地缓存的逻辑
 * @Author: pupil
 * @Date: 2024/07/10 下午 10:19
 */
public abstract class AbstractZookeeperRegistry implements RegistryService {

    // 服务注册
    @Override
    public void register(URL url) throws Exception {
        final Service serviceName = new Service(url.getServiceName(),url.getVersion());
        if (!Cache.SERVICE_URLS.containsKey(serviceName)){
            Cache.SERVICE_URLS.put(serviceName,new ArrayList<>());
        }
        Cache.SERVICE_URLS.get(serviceName).add(url);
    }

    // 服务销毁
    @Override
    public void unRegister(URL url) throws Exception {
        final Service serviceName = new Service(url.getServiceName(),url.getVersion());
        if (Cache.SERVICE_URLS.containsKey(serviceName)){
            Cache.SERVICE_URLS.remove(serviceName);
        }
    }

    // 服务发现
    @Override
    public List<URL> discoveries(String serviceName, String version) throws Exception {
        final Service key = new Service(serviceName, version);
        List<URL> urls = Cache.SERVICE_URLS.get(key);
        return urls;
    }
}
